<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";

require("echarts/theme/macarons"); // echarts theme

var myChart;
const runStateOption = [
  {
    label: "加工",
    value: 1000,
    color: "#46C13E",
  },
  {
    label: "报警",
    value: 2000,
    color: "#F80B18",
  },
  {
    label: "待机",
    value: 3000,
    color: "#FCCD0F",
  },
  {
    label: "离线",
    value: 4000,
    color: "#B9C6BA",
  },
  {
    label: "空闲",
    value: 0,
    color: "#ffffff",
  },
];
export default {
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "240px",
    },
    chartData: {
      type: Array,
      required: true,
    },
    chartColor: {
      type: Array,
      default: () => {
        return ["#3FC529", "#FBC225", "#E74629", "#E2E7EE"];
      },
    },
    titleShow: {
      type: Boolean,
      default: false,
    },
    running: {
      type: String,
      default: "240px",
    },
  },
  data() {
    return {
      chart: null,
      total: 11,
      themes: null,
    };
  },
  computed: {
    theme() {
      this.themes = this.$store.getters.thisTheme;
      this.initEcharts(this.chartData);
    },
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.initEcharts(val);
        // this.setOptions(val);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        myChart = echarts.init(this.$el, "macarons");
        this.initEcharts(this.chartData);
      }, 100);
      // this.initChart()
    });
  },
  // beforeDestroy() {
  //   if (!this.chart) {
  //     return
  //   }
  //   this.chart.dispose()
  //   this.chart = null
  // },
  methods: {
    // initChart() {
    //
    //   this.chart = echarts.init(this.$el, 'macarons')
    //   this.setOptions(this.chartData);
    // },
    // setOptions(chartData) {
    //   this.chart.setOption({
    //   })
    // },
    // methods: {
    isIos() {
      var ua = navigator.userAgent.toLocaleLowerCase();
      var u = navigator.userAgent;
      var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
      return isIOS;
    },

    formatDateToStr: function(fmt, date) {
      var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        S: date.getMilliseconds(), //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
      return fmt;
    },
    initEcharts(val) {
      let list = val;

      let array = [];
      for (var i = 0; i < list.length - 1; i++) {
        if (this.isIos()) {
          let time = list[i].time;
          let time1 = list[i + 1].time;
          list[i].time = time.replace(/-/g, "/");
          list[i + 1].time = time1.replace(/-/g, "/");
        }
        let runstate = list[i].runstate;
        let item = runStateOption.find((item) => item.value == runstate);
        array.push({
          itemStyle: {
            color: item.color,
          },
          label: item.label,
          value:
            new Date(list[i + 1].time).getTime() -
            new Date(list[i].time).getTime(),
          name:
            this.formatDateToStr("hh:mm:ss", new Date(list[i].time)) +
            "~" +
            this.formatDateToStr("hh:mm:ss", new Date(list[i + 1].time)),
        });
      }
      if (list.length > 0) {
        let lastTimeBefore = null;

        if (this.isIos()) {
          lastTimeBefore = list[list.length - 1].time;
          list[list.length - 1].time = lastTimeBefore.replace(/-/g, "/");
        }
        let lastTime = new Date(list[list.length - 1].time);
        let endTime = new Date(
          lastTime.getFullYear(),
          lastTime.getMonth(),
          lastTime.getDate(),
          23,
          59,
          59
        );

        let a = endTime.getTime() - lastTime.getTime();
        if (a > 1) {
          array.push({
            itemStyle: {
              color: "#ffffff",
            },
            label: "空闲",
            value: a,
            name:
              this.formatDateToStr("hh:mm:ss", lastTime) +
              "~" +
              this.formatDateToStr("hh:mm:ss", endTime),
          });
        }
      }
      // 蓝色海螺 Series Data
      var bluePieData = array;

      // 角度对应的时间
      var deg_clock = {
        0: 0,

        90: 6,

        180: 12,

        270: 18,

        360: 24,
      };

      // 区域带透明度的背景色
      var splitAreaColor = [
        "rgba(24, 237, 201,0.1)",
        "rgba(24, 237, 201,0.1)",
        "rgba(24, 237, 201,0.2)",
        "rgba(24, 237, 201,0.2)",
        "rgba(24, 237, 201,0.3)",
        "rgba(24, 237, 201,0.3)",
        "rgba(24, 237, 201,0.3)",
        "rgba(24, 237, 201,0.3)",
        "rgba(24, 237, 201,0.2)",
        "rgba(24, 237, 201,0.2)",
      ];

      /*-------------------------------------------------------------------------------------*/
      // 设置背景色
      // document.getElementsByTagName('body')[0].style.backgroundColor = "rgba(13, 17, 29)";

      var option = {
        polar: {
          radius: [82, 99],
          center: ["50%", "50%"],
        },
        // 极坐标
        angleAxis: {
          min: 0,
          max: 360,
          startAngle: 91,
          //         interval: 28,
          clockwise: true, //顺时针
          zlevel: 1,
          // 圆线
          axisLine: {
            show: false,
          },
          // 圆线上的刻度
          axisTick: {
            show: false,

            lineStyle: {
              color: "#000",
            },
          },
          // 圆线上的刻度标签
          axisLabel: {
            color: "#7C8CA5",
            interval: "2",
            fontWeight: "bold",
            formatter: function(deg) {
              return deg_clock[deg];
            },
          },
          // 圆中直区域分割线
          splitLine: {
            show: false,
            lineStyle: {
              color: ["rgba(26, 28, 38)"],
            },
          },
          // 圆中被分割的区域
          splitArea: {
            show: false,
            areaStyle: {
              color: splitAreaColor,
            },
          },
        },
        // 刻度
        axisTick: {
          show: false,
          lineStyle: {
            color: "#000",
          },
        },
        // 刻度标签
        axisLabel: {
          show: false,
        },
        radiusAxis: {
          show: false,
        },
        tooltip: {
          trigger: "item",
        },

        series: [
          {
            name: "blue",
            type: "pie",
            radius: [70, 90],
            center: ["50%", "50%"],
            // roseType: 'area', //是否展示成南丁格尔图，通过半径区分数据大小。可选择两种模式：radius/area
            tooltip: {
              show: false,
            },
            label: {
              show: true,
              position: "center",
              color: "rgba(13, 17, 29,0)",
            },
            emphasis: {
              label: {
                show: true,
                color: "#a9d2d3",
                fontSize: 12,
                lineHeight: 20,
                formatter: "加工" + this.running,
              },
            },
            labelLine: {
              show: false,
            },
            zlevel: 3,
            hoverAnimation: false, //hover时是否有放大效果
            clockwise: true, //饼图的扇区是否是顺时针排布
            startAngle: 90, //起始角度
            data: bluePieData,
          },
        ],
      };
      // myChart = echarts.init(document.getElementById('echarts'))
      // 观测更新的数据在 view 层可以直接访问到
      myChart.setOption(option);

      /*-------------------------------------------------------------------------------------*/

      var arr = [
        0,
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        10,
        11,
        12,
        13,
        14,
        15,
        16,
        17,
        18,
        19,
        20,
        21,
        22,
        23,
      ];

      // 默认高亮
      myChart.dispatchAction({
        type: "highlight",
        // 可选，系列 index，可以是一个数组指定多个系列
        seriesIndex: [0, 1],
        // 可选，数据的 index
        dataIndex: 0,
      });

      myChart.on(
        "mouseover",
        {
          seriesIndex: 0,
        },
        function(e) {
          // 取消高亮
          myChart.dispatchAction({
            type: "downplay",
            // 可选，系列 index，可以是一个数组指定多个系列
            seriesIndex: [0, 1],
            // 可选，数据的 index
            dataIndex: arr,
          });
          // 设置高亮
          myChart.dispatchAction({
            type: "highlight",
            // 可选，系列 index，可以是一个数组指定多个系列
            seriesIndex: [0, 1],
            // 可选，数据的 index
            dataIndex: e.dataIndex,
          });
          // 隐藏24小时图标
          myChart.dispatchAction({
            type: "hideTip",
            // 系列的 index，在 tooltip 的 trigger 为 axis 的时候可选。
            seriesIndex: [1],
            // 数据的 index，如果不指定也可以通过 name 属性根据名称指定数据
            dataIndex: arr,
          });
          // 显示24小时图标
          myChart.dispatchAction({
            type: "showTip",
            // 系列的 index，在 tooltip 的 trigger 为 axis 的时候可选。
            seriesIndex: [1],
            // 数据的 index，如果不指定也可以通过 name 属性根据名称指定数据
            dataIndex: e.dataIndex,
            // 本次显示 tooltip 的位置。只在本次 action 中生效。
            // 缺省则使用 option 中定义的 tooltip 位置。
            position: [100, 200],
          });
        }
      );
    },
    updateEcharts(newValue, oldValue, ownerInstance, instance) {
      // 监听 service 层数据变更
      myChart.setOption(newValue);
    },
    onClick(event, ownerInstance) {
      // 调用 service 层的方法
      ownerInstance.callMethod("onViewClick", {
        test: "test",
      });
    },
    // }
  },
};
</script>
